import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Card,
  Popconfirm,
  Divider,
  Button,
  Input,
  Modal,
  Drawer,
  Space,
  Tag,
  Table,
  Checkbox,
  Menu,
  Dropdown,
  message,
  Form,
  Row,
  Col,
} from 'antd';
import { connect, Link } from 'umi';
import moment from 'moment';
import MemberCou from './components/MemberCou';
import { DownOutlined, RightOutlined, SearchOutlined, SyncOutlined } from '@ant-design/icons';
import MemberDetail from './components/memberDtl';
import PushCoupon from './components/PushCoupon';
import { FormInstance } from 'antd/lib/form';

// const { Search } = Input;
class ViewPage extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      dataSource: [],
      visible: false,
      selectedRowKeys: [],
      pageIndex: 1,
      pageSize: 10,
      totalCount: 0,
      payload: {},
      visibleCou: false,
      couponMember: [],
      visibleCoued: false,
      couedId: '',
    };
  }

  formRef = React.createRef<FormInstance>();
  componentDidMount() {
    this.fetchDatas();
  }
  fetchDatas = () => {
    this.setState({ loading: true });
    const { pageIndex, pageSize, payload } = this.state;
    this.props
      .dispatch({
        type: 'Abp/getList',
        payload: { SkipCount: (pageIndex - 1) * pageSize, MaxResultCount: pageSize, ...payload },
        control: 'Members',
      })
      .then(() => {
        var resp = this.props.response;
        if (resp.result) {
          var dataSource = resp.result.items;
          this.setState({ loading: false, dataSource, totalCount: resp.result.totalCount });
        }
      });
  };
  handleDelete = (id: number) => {
    this.props
      .dispatch({
        type: 'Abp/delete',
        payload: { id },
        control: 'Members',
      })
      .then(() => {
        this.fetchDatas();
      });
  };
  handleResetPsw = (id: number) => {
    console.log(id);
    this.props.dispatch({
      type: 'Abp/resetPsw',
      payload: { id },
      control: 'Members',
    });
  };
  onSelectChange = (selectedRowKeys: any) => {
    this.setState({ selectedRowKeys });
  };
  onSearch = (value: any) => {
    var payload = this.state.payload;
    payload.nickname = value.nickname;
    payload.mobile = value.mobile;
    this.setState({ payload }, () => {
      this.fetchDatas();
    });
  };
  swithDrawer = (visible: boolean, record = null) => {
    this.setState({ visible, record });
  };
  swithCoupon = (visible: boolean, record = null, type: any) => {
    console.log(record);
    console.log(type);

    let { couponMember, selectedRowKeys } = this.state;
    console.log(selectedRowKeys);
    this.setState({ visibleCou: visible });
    if (type == 'batch') {
      this.setState({ couponMember: selectedRowKeys });
    }
    if (type == 'sole') {
      couponMember = [];
      couponMember.push(record);
      this.setState({ couponMember });
    }
    console.log(record);
    console.log(couponMember);
  };
  handleAction = (act: string) => {
    const { selectedRowKeys } = this.state;
    if (selectedRowKeys.length <= 0) {
      message.warning('请至少选择一位用户！');
      return;
    }
    console.log(selectedRowKeys);

    if (act == 'coupon') {
      this.swithCoupon(true, null, 'batch');
    }
  };
  handleMenuClick = (e: any) => {
    this.handleAction(e.key);
    // this.props
    //   .dispatch({
    //       type:'',
    //       payload:{},
    //       control:''
    //   }).then(()=>{
    //     var resp = this.props.response;
    //     if (resp && resp.success) {
    //       message.info('执行成功！');
    //       this.fetchDatas();
    //     }
    //   })
  };
  swithCouponed = (visible: any, record: any) => {
    this.setState({ visibleCoued: visible, couedId: record });
  };
  refresh = () => {
    this.formRef.current!.resetFields();
    this.setState({ payload: {} }, () => {
      this.fetchDatas();
    });
  };
  render() {
    const { loading, dataSource, selectedRowKeys, totalCount, pageSize } = this.state;
    const columns: any = [
      {
        title: '用户名',
        dataIndex: 'nickname',
      },
      {
        title: '手机号',
        dataIndex: 'mobile',
      },
      {
        title: '角色',
        dataIndex: 'role',
      },
      {
        title: '会员等级',
        dataIndex: 'tProduct',
        render: (text: string, record: any) => {
          if (record.tProduct == null) {
            return <Tag color="green">普通会员</Tag>;
          } else if (
            record.tProduct !== null &&
            moment(record.endDate).unix() >= moment(new Date()).unix()
          ) {
            return <Tag color="gold">VIP会员</Tag>;
          } else if (
            record.tProduct !== null &&
            moment(record.endDate).unix() < moment(new Date()).unix()
          ) {
            return <Tag color="gray">会员已过期</Tag>;
          }
        },
      },
      {
        title: 'VIP截止日期',
        dataIndex: 'endDate',
        render: (text: Date) => <span>{moment(text).format('YYYY-MM-DD hh:mm:ss')}</span>,
      },
      {
        title: '锁定',
        dataIndex: 'isLock',
        render: (text: boolean) => <Checkbox checked={text} />,
      },
      {
        title: '城市',
        dataIndex: 'city',
        render: (text: string) => <Tag color="blue">{text}</Tag>,
      },
      {
        title: '注册时间',
        dataIndex: 'creationTime',
        render: (text: Date) => <span>{moment(text).format('YYYY-MM-DD hh:mm:ss')}</span>,
      },
      {
        title: '操作',
        render: (record: any) =>
          dataSource.length >= 1 ? (
            <span>
              <Popconfirm title="确定删除?" onConfirm={() => this.handleDelete(record.id)}>
                <a>删除</a>
              </Popconfirm>
              <Divider type="vertical" />
              <a onClick={() => this.swithDrawer(true, record)}>查看</a>
              <Divider type="vertical" />
              <a>锁定</a>
              <Divider type="vertical" />
              <Popconfirm title="确定重置密码?" onConfirm={() => this.handleResetPsw(record.id)}>
                <a>重置密码</a>
              </Popconfirm>
              <Divider type="vertical" />
              <Link to={'./orders?mid=' + record.id}>查看订单</Link>
              <Divider type="vertical" />
              <a onClick={() => this.swithCoupon(true, record.id, 'sole')}>发放优惠券</a>
              <Divider type="vertical" />
              <a onClick={() => this.swithCouponed(true, record.id)}>已发放优惠券</a>
            </span>
          ) : null,
      },
    ];
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const menu = (
      <Menu onClick={this.handleMenuClick}>
        <Menu.Item key="coupon" icon={<RightOutlined />}>
          发放优惠券
        </Menu.Item>
        {/* <Menu.Item key="delete" icon={<RightOutlined />}>
          删除
        </Menu.Item> */}
      </Menu>
    );
    return (
      <PageHeaderWrapper>
        <Card>
          <Space>
            <Button type="primary" onClick={this.refresh} loading={loading} icon={<SyncOutlined />}>
              刷新
            </Button>
            <Dropdown overlay={menu}>
              <Button>
                操作 <DownOutlined />
              </Button>
            </Dropdown>
            {/* <Search
              style={{ width: 240 }}
              placeholder="输入关键词搜索"
              onSearch={(value) => this.onSearch(value)}
            /> */}
            <Form ref={this.formRef} onFinish={this.onSearch} style={{ height: 32 }}>
              <Row gutter={4}>
                <Col span={8}>
                  <Form.Item label="昵称" name="nickname">
                    <Input placeholder="请输入昵称" />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item label="手机号" name="mobile">
                    <Input placeholder="请输入手机号" />
                  </Form.Item>
                </Col>
                <Col span={2}>
                  <Form.Item>
                    <Button
                      type="primary"
                      icon={<SearchOutlined />}
                      htmlType="submit"
                      title="查询"
                      style={{ zIndex: 3 }}
                    >
                      搜索
                    </Button>
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </Space>
        </Card>
        <Table
          rowKey="id"
          loading={loading}
          rowSelection={rowSelection}
          columns={columns}
          dataSource={dataSource}
          pagination={{
            onChange: (page) => {
              this.setState({ pageIndex: page }, () => {
                this.fetchDatas();
              });
            },
            pageSize,
            total: totalCount,
          }}
        />
        <Drawer
          width={800}
          placement="right"
          closable={false}
          onClose={() => this.swithDrawer(false)}
          visible={this.state.visible}
          destroyOnClose={true}
        >
          <MemberDetail ParentData={this.state.record} />
        </Drawer>
        <Modal
          title="发放优惠券"
          visible={this.state.visibleCou}
          bodyStyle={{ padding: 24 }}
          destroyOnClose={true}
          onCancel={() => this.swithCoupon(false, null, null)}
          footer={false}
          width={800}
        >
          <PushCoupon memberId={this.state.couponMember} />
        </Modal>
        <Modal
          title="已发放优惠券"
          visible={this.state.visibleCoued}
          bodyStyle={{ padding: 24 }}
          destroyOnClose={true}
          onCancel={() => this.swithCouponed(false, null)}
          footer={false}
          width={1500}
        >
          <MemberCou couponId={this.state.couedId} />
        </Modal>
      </PageHeaderWrapper>
    );
  }
}
export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ViewPage);
